# Create your views here.
from django.http.response import HttpResponse
from django.utils.crypto import get_random_string
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from django.contrib.auth.hashers import make_password, check_password
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from LabsApp import settings

from LabsApp.settings import REGISTER_CAPTCHA_EXPIRES, SMS_CODE_EXPIRES
from apps.users.image_code import generate_captcha
from apps.users.models import User
from apps.users.sers import UserSer, UserRegEmailSer, StdUserSerializer

#  邮箱
# class


#  获取验证码
from celery_tasks import task_email, task_sms


class ImageCode(APIView):

    def get(self, request):
        text, image = generate_captcha()
        cache = get_redis_connection('image_code')
        cache.set(str(text), REGISTER_CAPTCHA_EXPIRES)
        content_type = 'image/png'
        return HttpResponse(image, content_type=content_type)


# 登录
class Login(APIView):

    def post(self, request):
        nickname = request.data.get("username")
        password1 = request.data.get("password")
        user = User.objects.filter(nickname=nickname).first()
        if check_password(password1, user.password) is True:
            return Response({'code': 200, 'message': '登录成功', 'username': nickname})
        else:
            return Response({'code': 500, 'message': '登录失败'})


# 给手机号发送短信
class SendNote(APIView):

    def post(self, request):
        try:
            phone = request.data.get('phone', None)
            cache = get_redis_connection('verify_code')
            if cache.get(phone):
                return Response({'data': {'message': '短信已发送，请%s秒再试' % SMS_CODE_EXPIRES}})
            code = get_random_string(length=4, allowed_chars='0123456789')
            task_sms.ronglianyun_sms_send.delay(phone, (code, SMS_CODE_EXPIRES))
            cache.set(phone, code, SMS_CODE_EXPIRES)
            return Response({'data': {'message': '短信发送成功，请注意查收'}})
        except:
            return Response({'data': {'message': '短信发送失败'}}, status=status.HTTP_400_BAD_REQUEST)


def genrate_token(data, expires=settings.VERIFY_EMAIL_TOKEN_EXPIRES):
    """
    根据data生成确认token
    """

    serializer = Serializer(settings.ITSDANGEROUS_SECRET_KEY, expires_in=expires)
    # 将信息加密并变成字符串
    token = serializer.dumps(data).decode()
    return token


# 正常使用手机号注册
class Register(APIView):

    permission_classes = ()
    serializer_class = StdUserSerializer

    def post(self, request):
        token = request.query_params.get('token', None)
        if token:
            user_info = genrate_token(token)
            if user_info:
                user = User.objects.create_user(
                    nickname=user_info['nickname'],
                    email=user_info['email'],
                    phone=user_info['phone']
                )
                user.set_password(user_info['password'])
                user.save()
                return Response({'data': {}, 'message': 'success'})
        return Response({'data': '验证失败', 'message': 'fail'}, status=status.HTTP_201_CREATED)


# 简单发送邮箱注册
class QuickRegister(APIView):

    permission_classes = ()
    serializer_class = UserRegEmailSer

    def post(self, request):
        # 验证相同参数
        serializer = self.serializer_class(data=request.data)
        # 验证通过发送确认注册邮件
        if serializer.is_valid(raise_exception=True):
            nickname = serializer.data.get("nickname")
            email = serializer.data.get("email")
            password = make_password(serializer.data.get("password"))
            user = {'nickname': nickname, "email": email, "password": password}
            confirm_token = genrate_token(user)
            task_email.send_verify_email.delay(email, confirm_token)
            return Response({'data': {}, 'message': '注册成功'})
        else:
            return Response({'data': serializer.errors, 'message': '参数错误'})


# 所有获取用户
class Users(APIView):
    def get(self, request):
        user = User.objects.all()
        ser = UserSer(user, many=True)
        return Response({'code': 200, 'message': '成功', 'data': ser.data})
